package com.permission_server.util;

import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Base64;

@Component
public class PhotoHandler {

    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;

    /**
     * 获取用户图像绝对路径
     *
     * @param mainPath 主目录
     * @return 用户图片File对象
     */
    public File getPhotoFile(String mainPath) {
        StringBuffer path = new StringBuffer();
        path.append(new File(UPLOAD_FOLDER).getAbsolutePath()).append("/").append(mainPath);
        return new File(path.toString());
    }

    /**
     * 保存用户图像
     *
     * @param file     用户上传文件
     * @param mainPath 主目录
     * @param subPath  子目录
     * @return File对象
     */
    public File savePhoto(MultipartFile file, String mainPath, String subPath, String fileName, boolean encodeFileName) {
        if (subPath != null) mainPath += "/" + subPath;

        File userPhotoFile = getPhotoFile(mainPath);
        if (!userPhotoFile.exists()) {
            userPhotoFile.mkdirs();
        }

        int index = file.getOriginalFilename().lastIndexOf(".");
        String prefix = file.getOriginalFilename().substring(0, index);
        String suffix = file.getOriginalFilename().substring(prefix.length());

        if (fileName != null){
            fileName += suffix;
        }else{
            fileName = file.getOriginalFilename();
        }

        if (encodeFileName) fileName = DigestUtil.md5Hex(prefix) + suffix;

        File saveFile = new File(userPhotoFile.getAbsolutePath() + "/" + fileName);
        try {
            file.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return saveFile;
    }

    /**
     * 保存用户图像
     *
     * @param file     用户上传文件
     * @param mainPath 主目录
     * @param fileName 文件名
     * @return File对象
     */
    public File savePhoto(MultipartFile file, String mainPath, String fileName) {
        return savePhoto(file, mainPath, null, fileName, false);
    }

    /**
     * 删除用户图像（递归删除）
     *
     * @param mainPath 主目录
     */
    public void deleteUserPhoto(String mainPath) {
        File userPhotoFile = getPhotoFile(mainPath);
        if (userPhotoFile.exists()) {
            Path directory = Paths.get(userPhotoFile.getAbsolutePath());
            try {
                Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
                        Files.delete(file); // 有效，因为它始终是一个文件
                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                        Files.delete(dir); //这将起作用，因为目录中的文件已被删除
                        return FileVisitResult.CONTINUE;
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
